<?php

namespace addons\alioss\service;

use app\common\service\ConfigService;
use app\common\AppService;
use OSS\Core\OssException;
use OSS\OssClient;

class UploadService extends AppService
{
    /**
     * @desc 阿里云上传
     * @param $param
     */
    public static function upload($param)
    {
        $path = $param[ "path" ];

        // 去掉开头的/
        $object = substr($path, 1);

        // 获取系统上传配置
        $uploadConfig = ConfigService::getConf('sys_upload', 'admin');

        if ($uploadConfig['type'] != 'alioss')
        {
            return self::error(400);
        }

        $config = ConfigService::getConf('addon_alioss', 'alioss');
        $accessKeyId = $config['key'];
        $accessKeySecret = $config['secret'];
        $endpoint = $config['endpoint'];
        $bucket = $config['bucket'];

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $result = $ossClient->uploadFile($bucket, $object, rootPath() . 'public/' . $path);

            if ($config['domain'])
            {
                $filePath = $config[ 'domain' ] . $path;
            } else {
                $filePath = $result[ "info" ][ "url" ];
            }

            //返回图片的完整URL
            return self::success(['path' => $filePath]);
        } catch (OssException $e) {
            return self::error(405, $e);
        }
    }
}